package com.web.controller.plumber;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.common.apiresult.CommonResult;
import com.common.apiresult.ResultCode;
import com.common.constant.RedisConstant;
import com.common.domain.dto.WaterElectricityQueryDTO;
import com.common.domain.dto.WaterElectricityUpdateDTO;
import com.common.utils.RedisUtil;
import com.service.serviceInterface.BuildingService;
import com.service.serviceInterface.DormService;
import com.service.serviceInterface.WaterElectricityService;
import com.service.utils.SecurityUtil;
import com.system.entity.Dorm;
import com.system.entity.WaterElectricity;
import com.web.entity.dto.WaterElectricityAddDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liuxuhuang
 * @date 2023年04月04日 11:39
 * @desc 宿舍水电费控制器
 */
@RestController(value = "plumberWaterElectricityController")
@Api(value = "waterElectricity", tags = "宿舍水电费控制器")
@RequestMapping(value = "/plumber/waterElectricity")
@Slf4j
public class WaterElectricityController {
    @Resource
    private WaterElectricityService waterElectricityService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private BuildingService buildingService;
    @Resource
    private DormService dormService;
    @Resource
    private SecurityUtil securityUtil;

    @GetMapping
    @ApiOperation(value = "获取水电费信息")
    public CommonResult getWaterElectricity(WaterElectricityQueryDTO dto) {
        return waterElectricityService.selectPage(dto, 0);
    }

    @PostMapping
    @ApiOperation(value = "添加水电费信息")
    public CommonResult addWaterElectricity(@RequestBody @Validated WaterElectricityAddDTO dto) {
        long userId = securityUtil.getUserId(SecurityContextHolder.getContext());
        WaterElectricity waterElectricity = new WaterElectricity();
        waterElectricity.setDormId(dto.getDormId()).setTime(dto.getTime().substring(0, 7))
                .setWaterConsum(Double.valueOf(dto.getWaterConSum())).setWaterCharge(Double.valueOf(dto.getWaterCharge()))
                .setElectricityConsum(Double.valueOf(dto.getElectricityConSum())).setElectricityCharge(Double.valueOf(dto.getElectricityCharge()))
                .setIsPay(0).setAddTime(LocalDateTime.now()).setAddUserId(userId);
        return waterElectricityService.save(waterElectricity) ? CommonResult.success() : CommonResult.failed();
    }

    @DeleteMapping
    @ApiOperation(value = "删除访客记录,只能删除未来的访客记录，不能删除过去的访客记录")
    public CommonResult delete(@RequestParam("id") @NotBlank(message = "参数不能为空") String id) {
        return waterElectricityService.delete(id);
    }

    @PutMapping
    @ApiOperation(value = "修改水电费信息")
    public CommonResult updateWaterElectricity(@RequestBody @Validated WaterElectricityUpdateDTO dto) {
        long userId = securityUtil.getUserId(SecurityContextHolder.getContext());
        boolean update = waterElectricityService.update(new LambdaUpdateWrapper<WaterElectricity>().set(WaterElectricity::getWaterConsum, dto.getWaterConsum())
                .set(WaterElectricity::getWaterCharge, dto.getWaterCharge()).set(WaterElectricity::getElectricityConsum, dto.getElectricityConsum())
                .set(WaterElectricity::getElectricityCharge, dto.getElectricityCharge()).set(WaterElectricity::getModifyTime, LocalDateTime.now())
                .set(WaterElectricity::getModifyUserId, userId).eq(WaterElectricity::getId, dto.getId()));
        return update ? CommonResult.success() : CommonResult.failed();
    }

    @GetMapping(value = "/getBuilds")
    @ApiOperation(value = "获取楼宇列表信息")
    public CommonResult getBuilds() {
        if (!redisUtil.hasKey(RedisConstant.BUILD_LIST)) {
            List buildingList = buildingService.list();
            redisUtil.setList(RedisConstant.BUILD_LIST, buildingList, 604800);
            return buildingList.size() > 0 ? CommonResult.success(buildingList) : CommonResult.failed(ResultCode.RETURNNULL);
        }
        List list = redisUtil.getList(RedisConstant.BUILD_LIST);
        return list.size() > 0 ? CommonResult.success(list) : CommonResult.failed(ResultCode.RETURNNULL);
    }

    @GetMapping(value = "/getDorms")
    @ApiOperation(value = "获取宿舍列表信息")
    public CommonResult getDorms(@RequestParam(value = "buildId") @NotBlank(message = "楼宇id不能为空") String buildId) {
        if (!redisUtil.hasKey(RedisConstant.DORM_LIST)) {
            List dormList = dormService.list();
            redisUtil.setList(RedisConstant.DORM_LIST, dormList, 604800);
        }
        List list = redisUtil.getList(RedisConstant.DORM_LIST);
        List<Dorm> dorms = new ArrayList<>();
        list.forEach(i -> {
            Dorm dorm = new Dorm();
            BeanUtils.copyProperties(i, dorm);
            dorms.add(dorm);
        });
        List<Dorm> dormList = dorms.stream().filter(j -> buildId.equals(j.getBuildingId().toString())).collect(Collectors.toList());
        return dormList.size() > 0 ? CommonResult.success(dormList) : CommonResult.failed(ResultCode.RETURNNULL);
    }
}
